<template>
  <Top-Page class="userSelection-wrap">
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <template #backText></template>
      <template #content>{{ title }}</template>
      <template #right>
        <view class="mr-10 f-16" @tap="save">
          {{ type == 3 ? "转发" : type == 4 ? "发送" : "保存" }}
        </view>
      </template>
    </cu-custom>
    <!--  :style="[{ top: CustomBar + 'px' }]" -->
    <view class="nav-box fixed bg-white">
      <view class="cu-bar search">
        <view class="search-form round" :class="[{ 'novice-guide-operate': !noviceGuide.includes(13) }]">
          <text class="cuIcon-search"></text>
          <input type="text" v-model="keywords" @focus="onfocus" placeholder="输入搜索的关键词" confirm-type="search" />
        </view>
      </view>
      <UserFiltrate
        @transmit="transmit"
        @changeShow="changeShow"
        :class="[
          {
            'novice-guide-operate': !noviceGuide.includes(14) && noviceGuide.includes(13),
          },
        ]"
        @selectCancel="selectCancel"
        :source="source"
      />
    </view>
    <!-- margin-top: 120rpx; -->
    <view
      @click="onChange"
      :class="[
        {
          'novice-guide-operate novice-guide-operate-1': !noviceGuide.includes(15) && noviceGuide.includes(14),
        },
      ]"
    >
      <view class="gui-padding" style="padding-bottom: 100rpx" v-if="!keywords && !forwarding_condition">
        <uni-data-checkbox
          multiple
          :max="groupUserMax"
          :mix="0"
          class="user-list-select"
          @change="chooseUser"
          v-model="changeUser"
          :localdata="lists"
        ></uni-data-checkbox>
        <Empty v-if="!lists.length" noDatatext="无联系人" textcolor="#999"></Empty>
      </view>
      <view
        class="gui-padding"
        style="margin-top: 120rpx; padding-bottom: 100rpx"
        v-if="keywords || !!forwarding_condition"
      >
        <uni-data-checkbox
          multiple
          :max="groupUserMax"
          :mix="0"
          class="user-list-select"
          @change="chooseSearchUser"
          v-model="searcheUser"
          :localdata="searchList"
        ></uni-data-checkbox>
        <Empty v-if="!searchList.length" noDatatext="未搜索到数据" textcolor="#999"></Empty>
      </view>
    </view>
    <view class="cu-bar bg-white tabbar border shop footer-opt">
      <scroll-view class="scroll-view_H" scroll-x="true" :scroll-anchoring="true" :scroll-left="scrollLeft">
        <view class="user-list-avatar">
          <template v-for="item in selectUser">
            <image class="user-avatar" :src="item.avatar" @tap="removeUser(item.id)"></image>
          </template>
        </view>
        <view class="select-num pd-10">已选{{ selectUser.length }}人</view>
      </scroll-view>
    </view>
    <view
      class="novice-guide-box"
      v-if="!noviceGuide.includes(13) || !noviceGuide.includes(14) || !noviceGuide.includes(15)"
    ></view>

    <view class="novice-guide-location-box" v-if="!noviceGuide.includes(13) || !noviceGuide.includes(14)">
      <template v-if="!noviceGuide.includes(13)">
        <view class="novice-guide-title">搜索好友创建群聊</view>
      </template>
      <template v-else-if="!noviceGuide.includes(14)">
        <view class="novice-guide-title">按条件筛选好友创建群聊</view>
      </template>
    </view>
    <view class="novice-guide-location-box-1" v-else-if="!noviceGuide.includes(15)">
      先选择好友，再点击右上角“保存”
    </view>
  </Top-Page>
</template>

<script>
import UserFiltrate from "@/components/User-Filtrate/User-Filtrate.vue";

import { useMsgStore } from "@/store/message";
import { storeToRefs } from "pinia";
import pinia from "@/store/index";
const msgStore = useMsgStore(pinia);
const { appendContacts } = storeToRefs(msgStore);
export default {
  components: {
    UserFiltrate,
  },
  data() {
    return {
      noviceGuide: uni.getStorageSync("noviceGuide") || [],
      forwarding_condition: null, //转发的条件
      sexChecked: [],
      age: 0,
      good_at: "", //技能事项
      hobby: "", //爱好
      groupUserNum: 0,
      groupUserMax: 1, //创建群组的最大值
      title: "发起群聊",
      contact_id: "",
      lists: [],
      originalList: [],
      eligibleList: [],
      keywords: "",
      searchList: [],
      selectUser: [],
      userList: [],
      changeUser: [], //选中的数据
      user_ids: [], //
      type: 1,
      source: "",
      relayState: false,
      scrollLeft: 300,
      contacList: [],
      searcheUser: [], //搜索选中人员
      curMsg: {},
      query: {},
    };
  },
  watch: {
    relayState(val) {
      if (val == true) {
        uni.showToast({
          icon: "success",
          title: "转发成功",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      }
    },
    keywords(val) {
      this.search();
      // 如果关键词为空 && 筛选条件为空，搜索选中的人员为已经选中的人员
      if (val != "" && !this.forwarding_condition) {
        this.searcheUser = this.changeUser;
      }
    },
    searcheUser(val) {
      const arr = this.changeUser.concat(val);
      console.log(arr, "arr");
      this.changeUser = [...new Set(arr)];
    },
  },

  onLoad(options) {
    var pages = getCurrentPages(); //当前页
    var beforePage = pages[pages.length - 2]; //上个页面
    this.type = options.type ? options.type : 1;
    this.contact_id = options.contact_id ? options.contact_id : "";
    this.source = options.source ?? "";
    this.query = options;

    msgStore.getContactsData();

    //创建群组的最大人数
    const globalConfig = JSON.parse(JSON.stringify(uni.getStorageSync("globalConfig") ?? "{}"));
    this.groupUserNum = (globalConfig.chatInfo.groupUserMax || 1) - 1;
    this.groupUserMax = 9999999;

    if (options.type == 2) {
      this.title = "添加成员";
      // 调用上一页的方法刷新
      // #ifdef H5
      this.user_ids = beforePage.user_ids;
      // #endif
      // #ifndef H5
      this.user_ids = beforePage.$vm.user_ids;
      // #endif
      this.getAllUser();
    } else if (options.type == 3) {
      this.title = "转发聊天";
      // 调用上一页的方法刷新
      // #ifdef H5
      this.curMsg = beforePage.curMsg;
      // #endif
      // #ifndef H5
      this.curMsg = beforePage.$vm.curMsg;
      // #endif
      this.getAllUser();
    } else {
      this.title = "发起群聊";
      this.getAllUser();
    }
  },
  methods: {
    onChange() {
      if (!this.noviceGuide.includes(15)) {
        this.noviceGuide.push(15);
        uni.setStorageSync("noviceGuide", this.noviceGuide);
      }
    },
    changeShow() {
      if (!this.noviceGuide.includes(14)) {
        this.noviceGuide.push(14);
        uni.setStorageSync("noviceGuide", this.noviceGuide);
      }
    },
    onfocus() {
      if (!this.noviceGuide.includes(13)) {
        this.noviceGuide.push(13);
        uni.setStorageSync("noviceGuide", this.noviceGuide);
      }
    },
    // 转发
    relay() {
      let user_ids = this.changeUser.map((it) => {
        return it.id;
      });
      if (!user_ids.length) {
        uni.showToast({
          title: "请选择至少一名人员",
          icon: "none",
        });
      } else if (user_ids.length > 5) {
        uni.showToast({
          title: "转发的人数不能超过5人！",
          icon: "none",
        });
      } else {
        var pages = getCurrentPages(); //当前页
        var beforePage = pages[pages.length - 2]; //上个页面
        let toContactId = "";
        let fromUser = "";
        // 调用上一页的方法刷新
        // #ifdef H5
        fromUser = beforePage.fromUser;
        toContactId = beforePage.contact.id;
        // #endif
        // #ifndef H5
        fromUser = beforePage.$vm.fromUser;
        // #endif
        let selectedItem = "";
        if (this.type == "relayCrm" || this.type == "relayProject") {
          // #ifdef H5
          selectedItem = beforePage.message;
          // #endif
          // #ifndef H5
          selectedItem = beforePage.$vm.message;
          // #endif
        } else {
          selectedItem = uni.getStorageSync("selectedItem");
        }
        user_ids.forEach((it) => {
          let msg = {
            id: this.$util.getUuid(),
            is_group: 0,
            fromUser,
            extends: selectedItem.extends ? selectedItem.extends : "",
            type: selectedItem.type,
            toContactId: it,
            content: selectedItem.content,
            sendTime: new Date().getTime(),
          };

          this.$api.msgApi.sendMessage(msg).then((res) => {
            if (res.code !== 200) return;
            this.relayState = true;
          });
        });
      }
    },
    transmit(data) {
      this.hobby = data.hobby ?? "";
      this.good_at = data.good_at ?? "";
      this.sexChecked = data.sexChecked ?? [];
      this.age = data.age ?? 0;

      this.searchUserList();
    },
    //取消搜索
    selectCancel() {
      this.lists = this.userList;
      this.groupUserMax = 9999999;
      this.forwarding_condition = null;

      //搜索选中的人员为已经选中的人员
      this.searcheUser = this.changeUser;
    },
    //搜索所有符合条件的用户
    searchUserList() {
      if (!this.hobby && !this.good_at && this.source !== "chat") {
        return uni.showToast({
          title: "请输入用户账号进行搜索",
          icon: "none",
        });
      }

      if (this.source === "chat") {
        this.forwarding_condition = {
          hobby: this.hobby,
          good_at: this.good_at,
          sexChecked: this.sexChecked,
          age: this.age,
        };

        this.search();
        return;
      }

      this.noText = "未搜索到数据";

      const data = {
        keywords: "",
        hobby: this.hobby,
        good_at: this.good_at,
        sexChecked: this.sexChecked.length ? this.sexChecked.join(",") : "",
        age: this.age,
      };

      this.$api.msgApi.searchUser(data).then((res) => {
        if (res.code == 0) {
          const data = res.data;

          this.eligibleList = data;
          this.lists.length = 0;

          if (Array.isArray(data) && data.length) {
            data.forEach((item) => {
              this.lists.push({
                ...item,
                value: item.user_id,
              });
            });
          }
          this.groupUserMax = this.groupUserNum < 1 ? 1 : this.groupUserNum;
          this.$forceUpdate();
        }
      });
    },
    // 移除群成员
    delUser() {
      uni.showModal({
        title: "提示",
        content: "确定删除？",
        cancelText: "取消", // 取消按钮的文字
        confirmText: "确认", // 确认按钮的文字
        showCancel: true, // 是否显示取消按钮，默认为 true
        success: (res) => {
          if (res.confirm) {
            var pages = getCurrentPages(); //当前页
            var beforePage = pages[pages.length - 2]; //上个页面
            // 调用上一页的方法刷新
            // #ifdef H5
            let group_id = beforePage.group_id;
            // #endif
            // #ifndef H5
            let group_id = beforePage.$vm.group_id;
            // #endif
            this.$api.msgApi
              .removeUser({
                user_id: this.changeUser.user_id,
                id: group_id,
              })
              .then((rr) => {
                if (rr.code !== 200) return;
                uni.navigateBack();
              });
          } else {
            console.log("cancel"); //点击取消之后执行的代码
          }
        },
      });
    },
    // 添加群成员
    addGroupUser(user_ids) {
      var pages = getCurrentPages(); //当前页
      var beforePage = pages[pages.length - 2]; //上个页面
      // 调用上一页的方法刷新
      // #ifdef H5
      beforePage.getsimpleMessage = false;
      let group_id = beforePage.group_id;
      // #endif
      // #ifndef H5
      beforePage.$vm.getsimpleMessage = false;
      let group_id = beforePage.$vm.group_id;
      // #endif
      this.$api.msgApi
        .addGroupUser({
          user_ids,
          id: group_id,
        })
        .then((res) => {
          if (res.code == 200) {
            uni.navigateBack();
          }
        });
    },
    // 添加群聊
    addGroup(user_ids) {
      this.$api.msgApi
        .addGroup({
          user_ids,
        })
        .then((res) => {
          if (res.code == 200) {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        });
    },
    getAllUser() {
      const allContact = uni.getStorageSync("allContacts");
      let contact = [];
      if (this.type == 3) {
        contact = allContact.filter((item) => {
          return item.id != this.contact_id && item.tempChat != 1;
        });
        contact.forEach((item) => {
          item.disable = false;
          let name = item.displayName;
          if (item.is_group) {
            name += "（群聊）";
          }
          item.text = name;
          item.value = item.id;
        });
      } else {
        contact = allContact.filter((item) => {
          return item.is_group == 0 && item.tempChat != 1;
        });
        this.contacList = JSON.parse(JSON.stringify(contact));
        contact.forEach((item) => {
          item.disable = false;
          item.text = item.displayName;
          item.value = item.id;
          if (this.user_ids.length && this.type == 2) {
            if (this.user_ids.includes(item.id)) {
              item.disable = true;
            }
          }
        });
        if (this.type == 1 && this.contact_id) {
          this.changeUser.push(parseInt(this.contact_id));
          this.selectUser = contact.filter((item) => {
            return item.id == this.contact_id;
          });
        }
      }
      this.userList = JSON.parse(JSON.stringify(contact));

      let lists = this.eligibleList.length ? this.eligibleList : contact;
      lists.forEach((item) => {
        item.identity != 1 && this.lists.push(item);
      });
      this.$forceUpdate();
    },
    chooseUser(e) {
      this.onChange();

      this.selectUser = e.detail.data;
      setTimeout(() => {
        this.scrollLeft += 300;
      }, 50);
    },
    chooseSearchUser(e) {
      this.onChange();
      this.selectUser = e.detail.data;
      // this.selectUser = this.$util.mergeArrays(
      // 	e.detail.data,
      // 	this.selectUser
      // );
      setTimeout(() => {
        this.scrollLeft += 300;
      }, 50);
    },
    removeUser(id) {
      this.selectUser = this.selectUser.filter((e) => {
        return e.id != id;
      });
      this.changeUser = this.changeUser.filter((e) => {
        return e != id;
      });
    },
    save() {
      const title = this.type == 3 ? "转发中..." : this.type == 4 ? "发送中..." : "保存中...";

      uni.showLoading({
        title: title,
        mask: true,
      });

      if (this.type == 2) {
        if (!this.changeUser.length) {
          uni.showToast({
            title: "请至少选择一个人！",
            icon: "none",
          });
          return;
        }
      } else {
        if (this.source != "chat" && this.changeUser.length < 2) {
          uni.showToast({
            title: "请至少选择两人！",
            icon: "none",
          });
          return;
        }
      }

      if (this.type == 1) {
        this.$api.msgApi.addGroup({ user_ids: this.changeUser }).then((res) => {
          uni.hideLoading();
          const data = res.data;
          msgStore.appendContacts(data);
          uni.navigateTo({
            url: "/pages/message/chat?id=" + data.id,
          });
        });
      } else if (this.type == 2) {
        this.$api.msgApi.addGroupUser({ user_ids: this.changeUser, id: this.contact_id }).then((res) => {
          uni.hideLoading();
          uni.navigateBack();
        });
      } else if (this.type == 3) {
        if (this.changeUser.length > 5) {
          return uni.showToast({
            title: "单次转发不能超过5人",
            icon: "none",
          });
        }
        this.$api.msgApi
          .forwardMessage({
            user_ids: this.changeUser,
            msg_id: this.curMsg.msg_id,
          })
          .then((res) => {
            // this.curMsg.msg_id = '';
            uni.hideLoading();
            uni.navigateBack();
          });
      } else if (this.type == 4) {
        if (this.changeUser.length > 5) {
          return uni.showToast({
            title: "单次发送不能超过5人",
            icon: "none",
          });
        }

        const user = uni.getStorageSync("userInfo");

        this.changeUser.forEach((id, index) => {
          let message = {
            type: "image",
            status: "going",
            content: this.query.transpond,
            toContactId: id,
            from_user: user.user_id,
            fromUser: user,
          };

          this.sendMessage(Object.assign(this.msgItem(), message));

          if (index === this.changeUser - 1) {
            uni.hideLoading();
            uni.showToast({
              title: "发送完成",
              icon: "none",
            });
            uni.navigateBack();
          }
        });
      } else {
        this.$api.msgApi.removeUser({ user_ids: this.changeUser, id: this.contact_id }).then((res) => {
          uni.hideLoading();
          uni.navigateBack();
        });
      }
    },
    sendMessage(message) {
      this.$api.msgApi.sendMessage(message).then((res) => {
        console.log("发送消息");
      });
    },
    msgItem() {
      return {
        id: this.$util.getUuid(),
        sendTime: new Date().getTime(),
        group_id: this.query.group_id ?? "",
        status: "going",
        type: "text",
        content: "",
        is_read: 0,
        is_group: 0,
        file_id: 0,
        file_cate: 0,
        fileName: "",
        fileSize: 0,
        extends: null,
      };
    },
    search: function (e) {
      let contact = JSON.parse(JSON.stringify(this.lists));
      const arr = this.$util.searchObject(
        contact,
        ["displayName", "name_py"],
        this.keywords,
        this.forwarding_condition
      );
      // this.searchList = arr;
      this.searchList.length = 0;
      this.searchList.push(...arr);
      this.$forceUpdate();
    },
    // 监听提交
    confirm: function (e) {
      let arr = [];
      if (e) {
        //这个值为输入框输入的值
        var brr = this.userList.filter((value) => {
          //遍历数组，返回值为true保留并复制到新数组，false则过滤掉
          let data = value.realname ? value.realname : value.userInfo.displayName;
          if (data.includes(e.trim())) {
            arr.push(value);
          }
          return data.includes(e.trim());
        });
        this.lists = arr;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.userSelection-wrap {
  padding-bottom: calc(var(--amplified_base) * 70rpx);
}
.search-warp {
  width: 750rpx;
  padding: 15rpx 50rpx;
}
.cu-bar {
  min-height: auto;
}
.nav-box {
  padding: 10rpx 0;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  padding-right: 20upx;
}
.search {
  flex: 1;
}
::v-deep .checklist-group {
  display: grid !important;
  .checklist-box {
    padding: 20rpx;
    .checkbox__inner {
      width: 40rpx !important;
      height: 40rpx !important;
      overflow: hidden;
      .checkbox__inner-icon {
        position: absolute;
        top: -8px !important;
        left: -4px !important;
        height: 20px !important;
        width: 20px !important;
        border-right-width: 2px !important;
        border-bottom-width: 2px !important;
      }
    }
    .checklist-content {
      margin-left: 20rpx;
      .checklist-text {
        font-size: calc(var(--amplified_base) * 36rpx) !important;
      }
    }
  }
}
.footer-opt {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}

.scroll-view_H {
  white-space: nowrap;
  width: 100%;
}

.user-list-avatar {
  float: left;
  margin-top: 10rpx;
  .user-avatar {
    width: calc(var(--amplified_base) * 70rpx);
    height: calc(var(--amplified_base) * 70rpx);
    flex: 0 0 auto;
    border-radius: 8rpx;
    margin-left: 15rpx;
    display: inline-block;
    &:last-child {
      margin-right: 15rpx;
    }
  }
  .select-num {
    padding: 10rpx;
  }
}

.label-li {
  border: none !important;
}

.novice-guide-location-box {
  bottom: auto;
  top: 200rpx;
}
.novice-guide-location-box-1 {
  position: fixed;
  padding: 20rpx;
  width: 100%;
  bottom: 100rpx;
  z-index: 999;
  color: #fff;
  font-size: calc(var(--amplified_base) * 48rpx);
  background-color: rgba(0, 0, 0, 0.8);
}
.novice-guide-operate-1 {
  background-color: #fff;
}
.btn-wrap {
  width: 100%;
  left: 0;
}
</style>
